﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
using gmeow.Core;
using gmeow.Framework;
using gmeow.UI;
using gmeow.UI.Properties;
using meow.displays.Growl;

namespace gmeow.UI
{
    public partial class MainForm : Form
    {
        private AccountRecord[] _accounts;
        private readonly FeedWatcher _fw;
        private IDisplay _display = new GrowlDisplay();

        public MainForm()
        {
            InitializeComponent();


            _fw = new FeedWatcher();
            _fw.NewContentHandler += new NewContent(_fw_NewContentHandler);
            
            _accounts = LoadAccounts();
            LoadFeeds(_accounts);
            
            if(_accounts != null 
                && Settings.Default.Interval >= 10)
            {
                _fw.Start(Settings.Default.Interval);
            }
            intervalBox.Text = Settings.Default.Interval+"";
            RefreshStartStop();
        }

        private void LoadFeeds(AccountRecord[] accounts)
        {
            if (accounts == null)
                return;

            _fw.Clear();
            foreach (AccountRecord record in accounts)
            {
                _fw.AddFeed(record.AccountName, "https://mail.google.com/mail/feed/atom",
                            record.Username,
                            record.Password);    
            }
        }

        void _fw_NewContentHandler(object sender, NewContentArgs args)
        {
            _display.Accept(args.FeedName,args.EntriesTitles,args.EntriesDescriptions );
        }
        private void RefreshStartStop()
        {
            startstopBtn.Text = _fw.IsRunning ? "Stop" : "Start";
            startstopBtn.Image = _fw.IsRunning ? Resources.control_stop_square : Resources.control;

        }
        private void accountsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            _accounts = LoadAccounts();
            Accounts ac = new Accounts(_accounts);
            ac.ShowDialog();
            _accounts = ac.AccountRecords;
            SaveAccounts(_accounts);
            LoadFeeds(_accounts);

        }

        private void SaveAccounts(AccountRecord[] accs)
        {
            // Construct a BinaryFormatter and use it to serialize the data to the stream.
            MemoryStream ms = new MemoryStream();

            BinaryFormatter formatter = new BinaryFormatter();
            try
            {
                formatter.Serialize(ms, accs);
            }
            catch (SerializationException e)
            {
                Console.WriteLine("crap. " + e.Message);
            }

            Settings.Default.AccountsBlob = Convert.ToBase64String(ms.ToArray());
            Settings.Default.Save();
        }

        private AccountRecord[] LoadAccounts()
        {
            byte[] s = Convert.FromBase64String(Settings.Default.AccountsBlob);
            MemoryStream ms = new MemoryStream(s);
            AccountRecord[] accs = null;
            try
            {
                BinaryFormatter formatter = new BinaryFormatter();
                 accs = (AccountRecord[]) formatter.Deserialize(ms);
            }
            catch (SerializationException e)
            {

            }

            return accs;
        }

        private void startstopBtn_Click(object sender, EventArgs e)
        {
            if(_fw.IsRunning)
            {
                _fw.Stop();
            }
            else
            {
                int p;
                int.TryParse(intervalBox.Text, out p);
                Settings.Default.Interval = Math.Max(p, 20);
                _fw.Start(Settings.Default.Interval);
                
            }
            RefreshStartStop();
        }

        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(e.CloseReason ==  CloseReason.UserClosing)
            {
                this.Hide();
                e.Cancel = true;
                return;
            }
            
            if (_fw.IsRunning)
                _fw.Stop();
        }

        private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (_fw.IsRunning)
                _fw.Stop();
            Application.Exit();
        }

    }
}
